<template>
  <!-- //危大工程范围 -->
  <a-modal title="选择危大工程范围" :visible="visible" class="large-modal" @ok="handleOk" @cancel="$emit('cancel', false)">
    <a-row v-loading="loading">
      <a-col :span="6">
        <div class="large-modal-div" style="height: 500px; border-right: 1px solid rgba(215, 215, 215, 1); padding-right: 10px; width: 100%; box-sizing: border-box">
          <a-spin :spinning="loading2" style="height: 100%">
            <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange" />
            <a-tree
              :selectedKeys.sync="selectedKeys"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :tree-data="gData"
              :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
              @expand="onExpand"
              @select="selectTreeNode"
            >
              <template slot="title" slot-scope="{ name, status }">
                <div class="ellipsis" :title="name">
                  <span v-if="name.indexOf(searchValue) > -1">
                    {{ name.substr(0, name.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span v-else>{{ name }}</span>
                  <span style="color: #ff4d4f">{{ !status ? '（停用）' : '' }}</span>
                </div>
              </template>
            </a-tree>
          </a-spin>
        </div>
      </a-col>
      <a-col :span="1" />
      <a-col :span="17">
        <searchData :search-data="searchArr" @search="search" />
        <list-table ref="table" row-key="id" :columns="columns" :request="loadData" :pageKeys="['pageNum', 'pageSize', 'total']" :row-selection="rowSelection">
          <template slot="enable" slot-scope="text">
            {{ text ? '可用' : '不可用' }}
          </template>
        </list-table>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.id
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
import { getLargeDangerConfigById, getPageLargeDangerDescConfig } from '@/api/technology'
export default {
  props: {
    visible: {
      type: Boolean,
      required: false
    },
    projectQualityTypeId: {
      //工程类别id
      type: String,
      required: ''
    },
    projectType: {
      type: String,
      required: '1'
    },
    parSelectedRows: {
      //选中的数据
      type: Array,
      required: []
    }
  },
  data() {
    return {
      selectedKeys: [],
      expandedKeys: [],
      autoExpandParent: true,
      gData: [],
      loading: false,
      loading2: false,
      dataList: [],
      searchValue: '',
      searchArr: [
        {
          name: '范围描述',
          value: 'desc',
          type: 'input'
        }
      ],
      columns: [
        {
          title: '范围描述',
          dataIndex: 'desc'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'enable' },
          width: 120
        }
      ],
      selectedRowKeys: [],
      selectedRows: [],
      arr:[],
    }
  },
  watch: {
    projectQualityTypeId: {
      handler(nv, old) {
        if (nv && old) {
          this.getLargeDangerConfigById(nv,true)
        }
      }
    },
    visible: {
      handler(nv, old) {
        if (nv) {
            this.selectedRowKeys = [];
            if(this.parSelectedRows?.length){   //回显
                this.selectedRows = this.parSelectedRows;
                this.parSelectedRows.map((item)=>{
                    this.selectedRowKeys.push(item.dangerProjectTypeId)
                })
            }
            
        }
      }
    },
    projectType:{
        immediate: true,
        handler(nv, old) {
        if (nv && old) {
          this.selectedRows = [];
            this.$nextTick(()=>{
                this.$refs?.table?.refresh(true)
            })
        }
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange,
          getCheckboxProps: record => ({
          props: {
            disabled: !record.status, 
          },
        }),

      }
    }
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      let temp = []
      selectedRows.map((v) => {
        let res = this.selectedRows.length && this.selectedRows.find((w) => v.id === w.id)
        if (!res) {
          temp.push(v)
        }
      })
      this.selectedRows = this.selectedRows.concat(temp)
      this.selectedRowKeys = selectedRowKeys

      console.log( this.selectedRows,1122,selectedRowKeys)
    },
    handleOk() {
      this.$emit('cancel', false, this.selectedRows)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange(e) {
      const value = e.target.value
      const expandedKeys = this.dataList
        .map((item) => {
          if (item.name.indexOf(value) > -1) {
            return getParentKey(item.key, this.gData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    selectTreeNode(selectedKeys, { node }) {
      this.selectedKeys = selectedKeys
      this.selectOrg = { ...node.dataRef, parentName: node.dataRef.parentId ? node.$parent.dataRef.name : '无' }
      if (node.dataRef.children && node.dataRef.children.length) {
        this.isLastNode = false
      } else {
        this.isLastNode = true
      }
      this.$refs.table.refresh(true)
    },
    // 获取树
    getLargeDangerConfigById(id, isInit = false) {
      this.loading2 = true
      this.selectedRows = [];
      getLargeDangerConfigById({ typeId: id }).then((res) => {
        this.dataList = []
        this.generateList(res.data)
        this.gData = this.getDataFn(res.data)
        this.loading2 = false
        //this.loadData();
        if (isInit) {
          this.selectedKeys = [this.gData[0].id]
          this.selectOrg = this.gData[0]
          this.$nextTick(() => {
            this.$refs.table.refresh(true)
          })
        }
      })
    },
    loadData(parameter) {
      const requestParameters = Object.assign({}, parameter, {
        param: {
          largeDangerId: this.selectOrg?.id,
          projectType: this.projectType*1===1?2:1,
          ...this.query
        }
      })
      if(this.selectOrg?.id){
        return getPageLargeDangerDescConfig(requestParameters).then((res) => {
        res.data.totalSize = res.data.total
        return res
      })
      }else{
        return {}
      }
      
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        node.scopedSlots = { title: 'title' }
        this.dataList.push(node)
        if (node.children && node.children.length > 0) {
          this.generateList(node.children)
        }
      }
    },
    search(val) {
      this.query = val
      this.$refs.table.refresh(true)
    },
    getDataFn(data) {
      data.forEach((item) => {
        if(!item.status){
            item.disabled = true;    //停用的不能选中
          }
        if (item.children?.length > 0) {
          this.getDataFn(item.children, item.disabled)
          item.disabled = true
        }
      })
      return data
    }
  },
  mounted() {
    this.projectQualityTypeId && this.getLargeDangerConfigById(this.projectQualityTypeId)
  }
}
</script>
<style scoped>
.large-modal-div{
  overflow: scroll;
}
</style>
